package com.ruoyi.pcj.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mashuai.utils.toolkit.core.msMp.MsDb;
import com.mashuai.utils.toolkit.core.msValidation.annotation.MsCheckObjParams;
import com.ruoyi.basis.service.MsBaseServiceImpl;
import com.ruoyi.basis.utils.mp.MpConditionUtils;
import com.ruoyi.basis.utils.mp.MpPageUtils;
import com.ruoyi.pcj.constant.TipConstant;
import com.ruoyi.pcj.domain.PcjLtFriendRecords;
import com.ruoyi.pcj.domain.PcjLtFriendSetting;
import com.ruoyi.pcj.mapper.PcjLtFriendRecordsMapper;
import com.ruoyi.pcj.service.IPcjLtFriendListService;
import com.ruoyi.pcj.service.IPcjLtFriendRecordsService;
import com.ruoyi.pcj.service.IPcjLtFriendSettingService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * 聊天-记录Service业务层处理
 *
 * @author ms
 * @date 2024-03-28
 */
@AllArgsConstructor
@Service
public class PcjLtFriendRecordsServiceImpl extends MsBaseServiceImpl<PcjLtFriendRecordsMapper, PcjLtFriendRecords> implements IPcjLtFriendRecordsService {
    private IPcjLtFriendListService friendListService;

    private IPcjLtFriendSettingService friendSettingService;

    @Override
    public <E extends IPage<PcjLtFriendRecords>> E page(E page, Wrapper<PcjLtFriendRecords> qw) {
        return baseMapper.selectPage(page, qw);
    }

    /**
     * 查询聊天-记录列表
     *
     * @param params 聊天室-查询参数 {"pageNum":1,"pageSize":10}
     * @return 聊天-记录
     */
    @Override
    public IPage<PcjLtFriendRecords> selectPcjLtFriendRecordsList(Map<String, Object> params) {
        //获取条件构造器
        QueryWrapper<PcjLtFriendRecords> qw = MpConditionUtils.getQueryWrapper(params, PcjLtFriendRecords.class);
        //分页查询
        Page<PcjLtFriendRecords> page = this.page(MpPageUtils.getPage(params), qw);
        return page;
    }


    /**
     * 根据id查询聊天-记录
     *
     * @param id 聊天-记录主键
     * @return 聊天-记录
     */
    @Override
    public PcjLtFriendRecords selectPcjLtFriendRecordsById(String id) {
        //首先获取主表信息
        PcjLtFriendRecords pcjLtFriendRecords = MsDb.getById(id, PcjLtFriendRecords.class);
        return pcjLtFriendRecords;
    }

    /**
     * 回填子表信息
     **/

    /**
     * 新增聊天-记录
     *
     * @param pcjLtFriendRecords 聊天-记录
     * @return 结果
     */
    @Override
    public Boolean insertPcjLtFriendRecords(PcjLtFriendRecords pcjLtFriendRecords) {
        //插入主表
        Boolean success = this.insertData(pcjLtFriendRecords);
        return success;
    }

    /**
     * 修改聊天-记录
     *
     * @param pcjLtFriendRecords 聊天-记录
     * @return 结果
     */
    @Override
    public Boolean updatePcjLtFriendRecords(PcjLtFriendRecords pcjLtFriendRecords) {
        //修改主表
        Boolean success = this.updateData(pcjLtFriendRecords);
        return success;
    }

    /**
     * 批量删除聊天-记录
     *
     * @param ids 需要删除的聊天-记录主键
     * @return 结果
     */
    @Override
    public Boolean deletePcjLtFriendRecordsByIds(String[] ids) {

        //删除主表
        Boolean success = this.removeBatchByIds(Arrays.asList(ids));
        return success;
    }
    /**
     * 根据主表id，删除子表所有数据
     **/
    /**
     * 对外提供的设置默认字段值，id为空新增，不为空更新
     **/
    @Override
    public void setEntityDefValAuto(PcjLtFriendRecords pcjLtFriendRecords) {
        this.setDefFieldVal(pcjLtFriendRecords);
    }

    @Transactional(rollbackFor = Exception.class)
    @MsCheckObjParams(keys = {"friendId", "content", "contentType"}, message = TipConstant.NO_PARAMS)
    @Override
    public PcjLtFriendRecords chat(Map<String, Object> params) {
        //接受参数
        //Long userId = SecurityUtils.getUserId();
        Long userId = MapUtils.getLong(params, "userId");
        Long friendId = MapUtils.getLong(params, "friendId");
        String content = MapUtils.getString(params, "content");
        String contentType = MapUtils.getString(params, "contentType");
        //先插入聊天记录
        PcjLtFriendRecords records = new PcjLtFriendRecords();
        records.setContentType(contentType);
        records.setContent(content);
        records.setStatus("0");//默认未读
        records.setSendUserId(userId);
        records.setReceiverUserId(friendId);
        records.setSendTime(new Date());
        this.insertData(records);
        //初始化好友设置
        initFriendSetting(userId, friendId, records);

        return records;
    }


    /**
     * 更新好友的设置信息
     **/
    private void initFriendSetting(Long userId, Long friendId, PcjLtFriendRecords records) {
        //判断当前用户对朋友的信息设置
        PcjLtFriendSetting userSetting = friendSettingService.initFriendSettingMsg(userId, friendId);
        PcjLtFriendSetting friendSetting = friendSettingService.getFriendSettingData(friendId, userId).get(0);
        //如果会话已经存在，则不更新
        if ("0".equals(userSetting.getSessionStatus())) {
            userSetting.setSessionStatus("1");
        }
        //如果非好友的时候，如果已经互发消息，那彼此成为好友
        if ("0".equals(userSetting.getStatus())) {
            //如果朋友已经发送过消息，可成好友
            Integer result = baseMapper.checkMutualChat(friendId);
            if (result > 0) {
                //获取好用对该用户的设置
                //同步更新两个的状态与成为好友时间
                Date nowTime = new Date();
                userSetting.setAddTime(nowTime);
                userSetting.setStatus("1");
                friendSetting.setAddTime(nowTime);
                friendSetting.setStatus("1");
            }
        }
        //更新双向的最新聊天时间，并且绑定最新一条聊天的聊天记录id
        Date nowTime = new Date();
        userSetting.setNewMsgTime(nowTime);
        userSetting.setNewMsgId(records.getId());
        friendSetting.setNewMsgTime(nowTime);
        friendSetting.setNewMsgId(records.getId());
        friendSettingService.updatePcjLtFriendSetting(userSetting);
        friendSettingService.updatePcjLtFriendSetting(friendSetting);
    }
}
